//封装VanFieldSelectPicker组件
<template>
  <div>
    <van-field
      v-model="resultLabel"
      v-bind="$attrs"
      clickable
      readonly
      @click="show = !show"
    />
    <van-popup v-model="show" position="bottom">
      <van-datetime-picker
        :type="type"
        @cancel="cancel"
        @confirm="onConfirm"
        @change="change"
      />
    </van-popup>
  </div>
</template>

<script>
import moment from "moment";

export default {
  name: "VanFieldDateTimePicker",
  model: {
    prop: "selectValue"
  },
  props: {
    selectValue: {
      type: [String, Date],
      default: ""
    },
    type: {
      type: String,
      default: "time"
    }
  },
  computed: {
    resultLabel: {
      //双向绑定的数据做修改需要用get/set
      get() {
        if (!this.resultValue) return "";
        if (this.type == "date") {
          return moment(this.resultValue).format("YYYY-MM-DD");
        } else if (this.type == "datetime") {
          return moment(this.resultValue).format("YYYY-MM-DD HH:mm:ss");
        } else {
          return this.resultValue;
        }
      },
      set() {}
    }
  },
  data() {
    return {
      show: false, //Popup是否弹出
      resultValue: this.selectValue //初始选中数据
    };
  },
  methods: {
    onConfirm(value) {
      //确定
      this.resultValue = value;
      this.show = !this.show;
      this.$emit("confirm", value, this.resultValue);
    },
    change(val) {
      //当数据改变
      this.$emit("change", val, this.resultValue);
    },
    cancel(val) {
      //取消
      this.show = !this.show;
      this.$emit("cancel", val, this.resultValue);
    }
  },
  watch: {
    selectValue: function(newVal) {
      //监听变化初始赋值
      this.resultValue = newVal;
    },
    resultValue(val) {
      //当所选数据变化，组件model的双向绑定
      this.$emit("input", val);
    }
  }
};
</script>
